package chen.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import chen.web.antispam.CaptchaStore;
import chen.web.antispam.CaptchaStore.VerifyResult;
import chen.web.controller.forum.JSONResponse;

/**
 * 当浏览器访问验证码图片时, 会存储验证码和用户的uuid. 
 * 验证时,会从根据uuid取出验证码和用户输入的验证码对比.
 * @author chen
 *
 */
@Controller
public class CaptchaController {
	
	private @Autowired CaptchaStore captchaStore;
	
	/**
	 * 
	 * @param uuid
	 * @param captcha
	 * @return
	 */
	@RequestMapping(value="/captcha/validate", method=RequestMethod.GET)
	public @ResponseBody JSONResponse ajaxValidate(@CookieValue("uuid") String uuid, @RequestParam String captcha){
		VerifyResult result = captchaStore.preVerify(uuid, captcha);
		if(result == VerifyResult.expired){
			return JSONResponse.errorMessage("验证码过期");
		}
		//验证码错误则立即移除验证码
		if(result == VerifyResult.failed){
			return JSONResponse.errorMessage("验证码错误");
		}
		return JSONResponse.successed();
	}
	
	@RequestMapping(value="/captcha", method=RequestMethod.GET)
	public void generatorCaptcha(@CookieValue("uuid") String uuid, HttpServletResponse response) throws IOException{
		if(uuid == null || uuid.trim().length() != 36){
			throw new IllegalArgumentException();
		}
        // Set to expire far in the past.
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
          
        // return a jpeg
        response.setContentType("image/jpeg");
        
        // create the image with the text
        BufferedImage bi = captchaStore.generateCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        
        ImageIO.write(bi, "jpg", out);
        
        out.flush();
	}
}
